import axios from 'axios';

const BASE_URL = 'http://127.0.0.1:8000/api/blog';

// 上传文件
export const uploadFile = async (blog_id, file) => {
  try {
    const formData = new FormData();
    formData.append('file', file);
    formData.append('blog_id', blog_id);

    const response = await axios.post(`${BASE_URL}/upload`, formData, {
      headers: {
        'Content-Type': 'multipart/form-data',
      },
    });

    return response.data;
  } catch (error) {
    throw new Error(error.response.data.message || 'File upload failed');
  }
};

// 下载文件
export const downloadFile = async (filename) => {
  try {
    const response = await axios.get(`${BASE_URL}/download/${filename}`, {
      responseType: 'blob',
    });

    const url = window.URL.createObjectURL(new Blob([response.data]));
    const link = document.createElement('a');
    link.href = url;
    link.setAttribute('download', filename);
    document.body.appendChild(link);
    link.click();
    link.remove();
  } catch (error) {
    throw new Error(error.response.data.message || 'File download failed');
  }
};

// 获取附件信息
export const getAttachmentsByBlogId = async (blogId) => {
  try {
    const response = await axios.get(`${BASE_URL}/attach/${blogId}`);
    return response.data;
  } catch (error) {
    throw new Error(error.response.data.message || 'Failed to fetch attachments');
  }
};
// import axios from 'axios';

// const BASE_URL = process.env.NEXT_PUBLIC_API_BASE_URL;

// // 上传文件
// export const uploadFile = async (blog_id, file) => {
//   try {
//     const formData = new FormData();
//     formData.append('file', file);
//     formData.append('blog_id', blog_id);

//     const response = await axios.post(`${BASE_URL}api/blog/upload`, formData, {
//       headers: {
//         'Content-Type': 'multipart/form-data',
//       },
//     });

//     return response.data;
//   } catch (error) {
//     throw new Error(error.response.data.message || 'File upload failed');
//   }
// };

// // 下载文件
// export const downloadFile = async (filename) => {
//   try {
//     const response = await axios.get(`${BASE_URL}api/blog/download/${filename}`, {
//       responseType: 'blob',
//     });

//     const url = window.URL.createObjectURL(new Blob([response.data]));
//     const link = document.createElement('a');
//     link.href = url;
//     link.setAttribute('download', filename);
//     document.body.appendChild(link);
//     link.click();
//     link.remove();
//   } catch (error) {
//     throw new Error(error.response.data.message || 'File download failed');
//   }
// };

// // 获取附件信息
// export const getAttachmentsByBlogId = async (blogId) => {
//   try {
//     const response = await axios.get(`${BASE_URL}api/blog/attach/${blogId}`);
//     return response.data;
//   } catch (error) {
//     throw new Error(error.response.data.message || 'Failed to fetch attachments');
//   }
// };
